package com.trip.admin;

import com.trip.api.ControllerResult;
import com.trip.dao.tables.pojos.AdminDomain;
import com.trip.def.CommonDefines;
import com.trip.exception.ServiceException;
import com.trip.service.AdminService;
import com.trip.util.StringUtil;
import com.trip.util.WebUtil;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by hc24 on 2017/12/16.
 */
@Controller
@Validated
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ControllerResult login(HttpServletRequest request, HttpSession session,
                                  @NotBlank(message ="Login name is empty" ) String loginName, @NotBlank(message = "Password is empty") String password){
        AdminDomain adminDomain= adminService.login(loginName,password, WebUtil.getIpAddr(request));
        session.setAttribute(CommonDefines.ADMIN_SESSION,adminDomain);
        return ControllerResult.success();
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }


}
